#include "Piston.h"
#include "Resource.h"

Piston::Piston(LPDIRECT3DDEVICE9 d3ddv,  LPDIRECT3DSURFACE9 backBuffer, LPD3DXSPRITE spriteHandler, float x, float y, int ID, int Object_State) : Object(x, y)
{
	this->setIDObjType(ID);

	p_sprite = new Sprite(spriteHandler, ResourceMng::GetInst(d3ddv, backBuffer)->GetTexture(ResourceMng::GetInst(d3ddv, backBuffer)->getMapTexture()[56]->getFileName()), 0, 0);
	
	width = p_sprite->getTexture()->getWidth();
	height = p_sprite->getTexture()->getHeight();

	veloc_y = PISTON_VY;

	pos_x = x;
	pos_y = y;

	pos_x_old = x;
	pos_y_old = y;

	pos_x_temp = x;
	pos_y_temp = y;

	max_distance = pos_y + 64;
	min_distance = pos_y;

	this->obj_state = Object_State;
}

Piston::~Piston()
{
	if (p_sprite)
	{
		delete p_sprite;
	}
}

void Piston::update(list<Object*>* obj_list, DxInput* input, float TPF)
{
	//Object::update(obj_list, input, TPF);
	width = p_sprite->getTexture()->getWidth();
	height = p_sprite->getTexture()->getHeight();

	pos_y_temp = pos_y;
	

	pos_y += veloc_y * TPF;
	if (pos_y < min_distance || pos_y > max_distance)
	{
		pos_y = pos_y_temp;
		veloc_y = -veloc_y;
	}

	//Object* obj;
	//list<Object*>::iterator i_obj;
	//for (i_obj = obj_list->begin(); i_obj != obj_list->end(); i_obj++)
	//{
	//	obj = *i_obj;
	//	Box box(this->pos_x_old,
	//		this->pos_y_old - this->height, 
	//		width, 
	//		height, 
	//		0, 
	//		veloc_y * TPF);

	//	Box block(obj->getPosX(),
	//		obj->getPosY() - obj->getHeight(),
	//		obj->getWidth(),
	//		obj->getHeight());

	//	Box boxphase = Collision::GetSweptBroadphaseBox(box);
	//	if (Collision::AABBCheck(boxphase, block))
	//	{
	//		float normalx = 0;
	//		float normaly = 0;
	//		float collision_time = Collision::SweptAABB(box, block, normalx, normaly);
	//		if (0 < collision_time && collision_time < 1)
	//		{
	//			if (obj->getObjectType() == OBJECT_LAND)
	//			{
	//				pos_y = pos_y_old;
	//				veloc_y = -veloc_y;
	//			}
	//		}
	//	}//end if
	//}//end for

	pos_y_temp = pos_y;


	if (pos_y > min_distance && pos_y < min_distance + 64/3)
	{
		p_sprite->setFrame(0,1);
		p_sprite->setIndex(0);
	}
	else if (pos_y > min_distance + 64/3 && pos_y < min_distance + 64/3 * 2)
	{
		p_sprite->setFrame(1,2);
		p_sprite->setIndex(1);
	}
	else if (pos_y > min_distance + 64/3 * 2 && pos_y < max_distance)
	{
		p_sprite->setFrame(2,3);
		p_sprite->setIndex(2);
	}

	p_sprite->update(TPF);
}

void Piston::render(int cameraX, int cameraY)
{
	//Object::render(cameraX, cameraY);
	p_sprite->render(pos_x, pos_y, cameraX, cameraY);
}

OBJECT_TYPE Piston::getObjectType()
{
	return OBJECT_LAND;
}